import json
import logging
import boto3


# 设置 AWS 访问密钥
# [profile Qa]
from numpy import NaN

# aws_access_key_id = "AKIASWZL2UIXMPQQ4NFT"
# aws_secret_access_key = "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"
#
# [profile Prod]
aws_access_key_id = "AKIAVGNWUKMQCF2NKKNR"
aws_secret_access_key = "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"

aws_region = 'us-east-2'
dynamodb = boto3.resource('dynamodb',
                          aws_access_key_id=aws_access_key_id,
                          aws_secret_access_key=aws_secret_access_key,
                          region_name=aws_region
                          )

iot_client = boto3.client(
    'iot',
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    region_name=aws_region
)

device_status_table = dynamodb.Table('device-status')


def getDeviceOnlineCountBySku(sku):
    try:
        iotOnlineCount = 0
        respIot = iot_client.search_index(queryString=f'connectivity.connected:true AND attributes.sku:{sku}')
        iotThings = respIot['things']
        iotOnlineCount += len(iotThings)
        while 'nextToken' in respIot:
            respIot = iot_client.search_index(queryString=f'connectivity.connected:true AND attributes.sku:{sku}',
                                              nextToken=respIot['nextToken'])
            iotThings = respIot['things']
            iotOnlineCount += len(iotThings)
        return iotOnlineCount
    except Exception as e:
        print(f"error{e}")
        return 0


def getDeviceConnectStatus(deviceId):
    try:
        respIot = iot_client.search_index(queryString=f'connectivity.connected:false AND thingName:{deviceId}')
        print(json.dumps(respIot['things'][0]))
    except Exception as e:
        print(f"error{e}")
        return 0


def saveMaxLifecycleEventToDeviceStatusTable(resGetCache):
    try:
        key = {}
        key['device_id'] = resGetCache['device_id']
        key['myuuid'] = resGetCache['myuuid']
        key['status'] = 1 if resGetCache['event_type'] == "connected" else 0
        key['version'] = resGetCache['version']
        key['event_timestamp'] = resGetCache['event_timestamp']
        response = device_status_table.put_item(Item=key)
        try:
            # print(response['ResponseMetadata'])
            statusCode = str(response['ResponseMetadata']['HTTPStatusCode'])
            # print(statusCode)
        except:
            statusCode = 0

        return {
            'statusCode': key,
            'result': "Success"
        }
    except Exception as e:
        logging.exception(e)
        return e


if __name__ == "__main__":
    getDeviceConnectStatus("108255a1-6d02-4742-9d93-1f0174ae38eb")
